<!--
 * @Author: 王坤
 * @LastEditors: 王坤
 * @Description: excel导出
-->
<template>
  <el-button class="lc-excel-export" v-bind="$attrs" :loading="isShowLoading" @click="handleDownload">
    <template v-if="iconPosition === 'right'">
      {{ label }}
    </template>
    <i v-if="isShowIcon" :style="iconPosition === 'right' ? 'margin-left: 4px' : 'margin-right: 4px'">
      <slot></slot>
    </i>
    <template v-if="iconPosition === 'left'">
      {{ label }}
    </template>
  </el-button>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { request } from '@/apis/request';
import { downloadFile } from '@/utils/common';
const props = defineProps({
  // 内容
  label: {
    type: String,
    default: ''
  },
  // 导出的url
  action: {
    type: String,
    default: ''
  },
  // 导出url请求类型
  method: {
    type: String,
    default: 'get'
  },
  // 导出的请求头部
  headers: {
    type: Object,
    default: () => ({})
  },
  // 导出附带的额外参数
  data: {
    type: Object,
    default: () => ({})
  },
  // 设置导出请求的返回数据类型
  responseType: {
    type: String,
    default: 'json'
  },
  isShowIcon: {
    type: Boolean,
    default: true
  },
  iconPosition: {
    type: String,
    default: 'left'
  }
});
const isShowLoading = ref(false);
// 文件下载
async function handleDownload() {
  if (!props.action) {
    ElMessage.warning({ message: '暂无可用的下载路径' });
    return;
  }
  try {
    const res = await request({
      url: props.action,
      method: props.method,
      headers: props.headers,
      params: props.data,
      data: props.data,
      responseType: props.responseType
    });
    downloadFile(res);
  } catch (error) {
    console.error(error);
  }
}
</script>
